package com.ergwang.controller.admin;

import com.ergwang.Model.Goods;
import com.ergwang.Model.Spec;
import com.ergwang.Model.admin.bo.*;
import com.ergwang.Model.Result;
import com.ergwang.Model.Type;
import com.ergwang.Model.admin.vo.GoodsInfoVO;
import com.ergwang.Model.admin.vo.Msg_NoRepliedVO;
import com.ergwang.Model.admin.vo.Msg_RepliedVO;
import com.ergwang.service.admin.GoodsService;
import com.ergwang.service.admin.GoodsServiceImpl;
import com.ergwang.service.admin.MsgService;
import com.ergwang.service.admin.MsgServiceImpl;
import com.ergwang.utils.FileUploadUtils;
import com.ergwang.utils.HttpUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author：ergwang
 * @Date: 2020/5/30
 * @Time: 15:07
 */
@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {

    private GoodsService goodsService = new GoodsServiceImpl();
    private MsgService msgService = new MsgServiceImpl();
    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");
        if ("addType".equals(action)){
            addType(request,response);
        }else if ("imgUpload".equals(action)){
            imgUpload(request,response);
        }else if ("addGoods".equals(action)){
            addGoods(request,response);
        }else if ("addSpec".equals(action)){
            addSpec(request,response);
        }else if ("deleteSpec".equals(action)){
            deleteSpec(request,response);
        }else if ("updateGoods".equals(action)){
            updateGoods(request,response);
        }else if ("reply".equals(action)){
            msg_reply(request,response);
        }
    }

    /**
     * 回复留言 返回code：0
     * @param request
     * @param response
     */
    private void msg_reply(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        MassageReplyBO msgReplyBO = gson.fromJson(requestBody, MassageReplyBO.class);
        goodsService.msg_reply(msgReplyBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 从请求中获取json数据，根据id更新商品信息
     * @param request
     * @param response
     */
    private void updateGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Goods goods = gson.fromJson(requestBody, Goods.class);
        goodsService.updateGoods(goods);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 根据请求携带的json数据，删除对应的spec
     * @param request
     * @param response
     */
    private void deleteSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Spec deleteSpec = gson.fromJson(requestBody, Spec.class);
        goodsService.deleteSpec(deleteSpec);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 根据id 为对应的商品添加规格
     * @param request
     * @param response
     */
    private void addSpec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        Spec addSpec = gson.fromJson(requestBody, Spec.class);
        Spec spec = goodsService.addSpec(addSpec);
        response.getWriter().println(gson.toJson(Result.ok(spec)));
    }

    /**
     * 添加商品
     * 1. 获取求体中的参数，然后将goods部分存入goods表
     * 2. 获取存入商品的 id --> goodsId
     * 3. 将剩下的规格部分和goodsId一块存入 规格表，
     * 4. 响应，添加成功！
     * @param request
     * @param response
     */
    private void addGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsBO goodsBO = gson.fromJson(requestBody, GoodsBO.class);
        goodsService.addGoods(goodsBO);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 新增商品中的图片上传的业务逻辑
     * commons-fileUpload
     * 1. 执行具体业务，上传图片
     * 2. 抓服务器上的响应报文
     * @param request
     * @param response
     */
    private void imgUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = FileUploadUtils.parseRequest(request);
        String file = (String) map.get("file");

        // ！特别注意：     ！！！！！！！！！！！！！！
        // 服务器上面的路径没有携带域名端口号，图片就会从当前服务器的端口去取
        // 如果图片和页面不在同一个域，则需要全路径来指明文件所在的域
        // 如：页面在8085，图片和数据在8084

        String domain = (String) getServletContext().getAttribute("domain");
        response.getWriter().println(gson.toJson(Result.ok(domain + file)));
    }

    /**
     * 根据请求中所携带的json数据，获得一个typeBO，然后创建一个新的type字段(类型)
     * @param request
     * @param response
     */
    private void addType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        GoodsTypeBO goodsTypeBO = gson.fromJson(requestBody, GoodsTypeBO.class);
        int addType = goodsService.addType(goodsTypeBO);
        if (addType != 0){
            response.getWriter().println(gson.toJson(Result.ok()));
        }else {
            response.getWriter().println(gson.toJson(Result.error("添加失败！请重试")));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/goods/", "");

        if ("getType".equals(action)){
            getType(request,response);
        }else if ("getGoodsByType".equals(action)){
            getGoodsByType(request,response);
        }else if ("deleteGoods".equals(action)){
            deleteGoods(request,response);
        }else if ("getGoodsInfo".equals(action)){
            getGoodsInfo(request,response);
        }else if ("deleteType".equals(action)){
            deleteType(request,response);
        }else if ("noReplyMsg".equals(action)){
            noReplyMsg(request,response);
        }else if ("repliedMsg".equals(action)){
            repliedMsg(request,response);
        }
    }

    /**
     * 已回复的留言列表
     * state = 0
     * @param request
     * @param response
     */
    private void repliedMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 默认state = 0，其他都和未回复一样,只是都一个参数replyContent
        int state = 0;
        List<Msg_RepliedVO> RepliedVOList = msgService.ReplyMsg(state);
        response.getWriter().println(gson.toJson(Result.ok(RepliedVOList)));
    }

    /**
     * 获取未回复的留言，返回给前端
     *  没有请求体的请求(其实是有的，state = 1)
     * @param request
     * @param response
     */
    private void noReplyMsg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 给个默认的state = 1
        int state = 1;
        List<Msg_NoRepliedVO> noRepliedVOList = msgService.noReplyMsg(state);
        response.getWriter().println(gson.toJson(Result.ok(noRepliedVOList)));
    }

    /**
     * 根据typeid 删除
     * @param request
     * @param response
     */
    private void deleteType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        goodsService.deleteType(typeId);
        response.getWriter().println(gson.toJson(Result.ok()));
    }

    /**
     * 根据get请求中携带的id 查询商品信息并返回
     * @param request
     * @param response
     */
    private void getGoodsInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        GoodsInfoBO goods = new GoodsInfoBO();
        goods.setId(id);
        List<SpecInfoBO> specInfoS = new ArrayList<SpecInfoBO>();
        GoodsInfoVO goodsInfoVO = new GoodsInfoVO(specInfoS,goods);
        goodsInfoVO = goodsService.getGoodsInfo(goodsInfoVO);
        Result result = new Result();
        result.setCode(0);
        result.setData(goodsInfoVO);
        response.getWriter().println(gson.toJson(result));
    }

    /**
     * 根据请求中的id 获取商品信息并删除
     * @param request
     * @param response
     */
    private void deleteGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        // 返回int 判断是否影响了行
        int delete = goodsService.deleteGoods(id);
        if (delete != 0){
            response.getWriter().println(gson.toJson(Result.ok("删除成功！")));
        } else {
            response.getWriter().println(gson.toJson(Result.ok("删除失败！请重试")));
        }
    }

    /**
     * 根据请求中的typeId获取该类型的所有商品
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<Goods> goodsList = goodsService.getGoodsByType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goodsList)));
    }

    /**
     * 加载商品的所有的分类
     *  1. 无参数
     * @param request
     * @param response
     */
    private void getType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Type> typeList = goodsService.getType();
        response.getWriter().println(gson.toJson(Result.ok(typeList)));
    }
}
